package cn.zkw.controller;

import cn.zkw.service.ArticleService;
import cn.zkw.service.NoticeService;
import cn.zkw.service.UserService;
import cn.zkw.service.WordsService;
import cn.zkw.util.UserUtil;
import cn.zkw.util.action.AbstractAction;
import cn.zkw.util.encrypt.MyPasswordEncrypt;
import cn.zkw.vo.*;
import net.sf.json.JSONObject;
import org.apache.commons.collections.bag.SynchronizedSortedBag;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

@SuppressWarnings("ALL")
@Controller
public class UserController extends AbstractAction {
    Logger logger = Logger.getLogger("UserController");
    @Resource
    UserService userService;

    @Autowired
    ArticleService articleService;

    @Autowired
    NoticeService noticeService;

    @Autowired
    WordsService wordsService;

    /**
     * 生日修改
     * @param user_birthday
     * @return
     */
    @RequestMapping(value = "/updateBirthday",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    public @ResponseBody Object updateBirthdayById(Date user_birthday){
        User user = new User();
        logger.info("更新生日"+user_birthday);
        user.setUser_name(String.valueOf(SecurityUtils.getSubject().getPrincipal()));
        user.setUser_birthday(user_birthday);
        JSONObject jsonObject = new JSONObject();
        if(userService.updateBirthdayById(user)){
            jsonObject.put("code",200);
        }else{
            jsonObject.put("code",304);
        }
        return jsonObject;
    }

    /**
     * 性别修改
     * @param user_sex
     * @return
     */
    @RequestMapping(value = "/updateSex", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody Object updateUserSexById(@RequestParam String user_sex){
        Integer sex = Integer.parseInt(user_sex);
        User user = new User();
        user.setUser_sex(sex);
        user.setUser_name(String.valueOf(SecurityUtils.getSubject().getPrincipal()));
        JSONObject jsonObject = new JSONObject();
        if(userService.updateSexById(user)){
            jsonObject.put("code",200);
        }else{
            jsonObject.put("code",201);
        }
        return jsonObject;
    }

    /**
     * 根据当前登陆的账号更新用户名
     * @param user_nickname
     * @return
     */
    @RequestMapping(value = "/updateUserName", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody Object updateUserName(String user_nickname){
        logger.info("updateUserName-user_name:"+SecurityUtils.getSubject().getPrincipal());
        User user = new User();//new一个user对象传给mybatis
        logger.info("修改的用户名:"+user_nickname);
        user.setUser_nickname(user_nickname); //传入要修改的昵称
        user.setUser_name((String)SecurityUtils.getSubject().getPrincipal());  //传入要修改的账号
        JSONObject jsonObject = new JSONObject();//接口数据的返回
        if(userService.updateNikeName(user)){
            jsonObject.put("code",200);
        }else{
            jsonObject.put("code",201);
        }

        return jsonObject;
    }

    /**
     * 检测同名账号接口
     * @param user_name
     * @return
     */
    @RequestMapping(value = "/registGetUser", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object registGetUser(String user_name) {
        JSONObject jsonObject = new JSONObject();
        if (userService.getUserByName(user_name) != null) {
            jsonObject.put("code", 201);
            jsonObject.put("msg", "账号已存在");
        } else {
            jsonObject.put("code", 200);
            jsonObject.put("msg", "可以使用的账号");
        }
        return jsonObject;
    }

    /**
     * 注册账号接口
     * @param user
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addUserRest", method = RequestMethod.POST,produces = "application/json")
    public @ResponseBody
    Object addUserRestful(User user, HttpServletRequest request) throws Exception {
        JSONObject jsonObject = new JSONObject();
        String password = MyPasswordEncrypt.encryptPassword(user.getUser_password());
        user.setUser_password(password);
        user.setUser_lock(0); //用户默认不锁定
        user.setUser_level(1); //用户默认等级为一级
        user.setUser_ip(request.getRemoteAddr());  //ip
        user.setUser_photo("nophoto.jpg");  //头像名称
        user.setUser_registration_time(new Date()); //注册时间
        user.setUser_rights(1);  //默认权限为一，，表示不是会员
        if (userService.getUserByName(user.getUser_name()) == null) {
            if (userService.addUser(user)) {
                jsonObject.put("code",200);
                jsonObject.put("msg", "注册成功！");
                return jsonObject;
            } else {
                jsonObject.put("code",304);
                jsonObject.put("msg", "出现异常,注册失败，请联系管理员！");
            }
        } else {
            jsonObject.put("code",304);
            jsonObject.put("msg", "注册失败，账号已存在！");
        }
        return jsonObject;
    }

    /**
     * qq登录并注册
     * 如果第一次登录就注册
     * @param openId
     * @return
     * @throws Exception
     */
    @RequestMapping(value="QQLoginUserRest",method = RequestMethod.POST,produces = "application/json")
    public @ResponseBody Object addUserRest(HttpServletRequest request,String openId,String nick,String headurl,String accessToken) throws Exception{
        JSONObject jsonObject = new JSONObject();
        User user = new User();
        user.setUser_name(openId);//qqID
        user.setUser_photo(headurl);//qq头像路径
        user.setUser_nickname(nick);//qq昵称
        user.setUser_birthday(new Date());//用户生日,设置默认值,让用户自己改
        request.getSession().getServletContext().setAttribute("accessToken",accessToken);
        request.getSession().getServletContext().setAttribute("openId",openId);
        String password = MyPasswordEncrypt.encryptPassword("123");
        user.setUser_password(password);
        user.setUser_lock(0); //用户默认不锁定
        user.setUser_level(1); //用户默认等级为一级
        user.setUser_ip(request.getRemoteAddr());  //ip
        user.setUser_registration_time(new Date()); //注册时间
        user.setUser_rights(1);  //默认权限为一，，表示不是会员

        if (userService.getUserByName(user.getUser_name()) == null) {
            if (userService.addUser(user)) {
                jsonObject.put("msg","初次登录,信息已存入数据库");
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(user.getUser_name(), "123");
                try {
                    subject.login(token);
                } catch (UnknownAccountException e) {
                    jsonObject.put("code", 201);
                    jsonObject.put("msg", "账号不存在");
                } catch (LockedAccountException e) {
                    jsonObject.put("code", 201);
                    jsonObject.put("msg", "账户被锁定");
                } catch (IncorrectCredentialsException e) {
                    jsonObject.put("code", 201);
                    jsonObject.put("msg", "密码错误");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                jsonObject.put("msg","登录失败,数据录入失败");
            }
        } else {
            User findUser = userService.getUserByName(user.getUser_name());
            jsonObject.put("code", 200);
            jsonObject.put("msg", "登陆成功");
            jsonObject.put("user",findUser);
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(findUser.getUser_name(), "123");
            try {
                subject.login(token);
            } catch (UnknownAccountException e) {
                jsonObject.put("code", 201);
                jsonObject.put("msg", "账号不存在");
            } catch (LockedAccountException e) {
                jsonObject.put("code", 201);
                jsonObject.put("msg", "账户被锁定");
            } catch (IncorrectCredentialsException e) {
                jsonObject.put("code", 201);
                jsonObject.put("msg", "密码错误");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }


    /**
     * 注册账号
     * @param user
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public @ResponseBody
    Object addUser(User user, HttpServletRequest request) throws Exception {
        System.out.println(request.getRemoteAddr());
        System.out.println(user);
        ModelAndView modelAndView = new ModelAndView("front/tip");
        String password = MyPasswordEncrypt.encryptPassword(user.getUser_password());
        user.setUser_password(password);
        user.setUser_lock(0); //用户默认不锁定
        user.setUser_level(1); //用户默认等级为一级
        user.setUser_ip(request.getRemoteAddr());  //ip
        user.setUser_photo("nophoto.jpg");  //头像文件名
        user.setUser_registration_time(new Date()); //注册时间
        user.setUser_rights(1);  //默认权限为一，，表示不是会员

        if (userService.getUserByName(user.getUser_name()) == null) {
            if (userService.addUser(user)) {
                modelAndView.addObject("msg", "注册成功！");
                modelAndView.addObject("url", "index");
                return modelAndView;
            } else {
                modelAndView.addObject("msg", "出现异常,注册失败，请联系管理员！");
                modelAndView.addObject("url", "userAdd");
            }
        } else {
            modelAndView.addObject("msg", "注册失败，账号已存在！");
            modelAndView.addObject("url", "userAdd");
        }
        return modelAndView;
    }


    /**
     * 登陆注销
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/loginOut", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object loginOut(HttpServletRequest request) throws Exception {
        request.getSession().setAttribute("name", null);
        request.getSession().setAttribute("photo", null);
        JSONObject jsonObject = new JSONObject();
        try {
            SecurityUtils.getSubject().logout();
        } catch (Exception e) {
            jsonObject.put("msg", "注销失败");
            jsonObject.put("code", 202);
        }
        jsonObject.put("msg", "注销成功");
        jsonObject.put("url", "index");
        jsonObject.put("code", 200);
        return jsonObject;
    }

    /**
     * 登陆功能
     * @param user
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object login(User user, HttpServletRequest request) throws Exception {
        JSONObject jsonObject = new JSONObject();
        User findUser = userService.getUserByName(user.getUser_name()); //查询用户
        jsonObject.put("code", 200);
        jsonObject.put("msg", "登陆成功");
        jsonObject.put("user",findUser);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUser_name(), user.getUser_password());
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            jsonObject.put("code", 201);
            jsonObject.put("msg", "账号不存在");
        } catch (LockedAccountException e) {
            jsonObject.put("code", 201);
            jsonObject.put("msg", "账户被锁定");
        } catch (IncorrectCredentialsException e) {
            jsonObject.put("code", 201);
            jsonObject.put("msg", "密码错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


    @RequestMapping("userAdd")
    public String userAdd() {
        return "front/userAdd";
    }

    /**
     * webapp登陆接口
     * @param user
     * @param request
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "/login2", method = {RequestMethod.POST,RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object login2(@RequestBody User user, HttpServletRequest request) throws Exception {
//        User user= new User();
//        user.setUser_name(user_name);
//        user.setUser_password(user_password);
        System.out.println(user+"***********");
        JSONObject jsonObject = new JSONObject();
        User findUser = userService.getUserByName(user.getUser_name()); //查询用户
        jsonObject.put("code", 200);
        jsonObject.put("result",true);
        jsonObject.put("msg", "登陆成功");
        jsonObject.put("user",findUser);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUser_name(), user.getUser_password());
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            jsonObject.put("code", 201);
            jsonObject.put("msg", "账号不存在");
            jsonObject.put("result",false);
        } catch (LockedAccountException e) {
            jsonObject.put("code", 201);
            jsonObject.put("msg", "账户被锁定");
            jsonObject.put("result",false);
        } catch (IncorrectCredentialsException e) {
            jsonObject.put("code", 201);
            jsonObject.put("msg", "密码错误");
            jsonObject.put("result",false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * POST
     * 根据请求,查询文章
     * @param sort 文章种类,0为无条件,1为前端技术,2为后端技术.....
     * @param request
     * @return
     */
    @RequestMapping(value = "index")
    public String indexPost(Integer sort_id,String keyword,HttpServletRequest request) {
        //公告信息初始化,给sidebar，因为很多页面跳转都需要给sidebar加载初始化信息，所以就在这里用application范围初始化了
        List<Notice> list =  noticeService.selectAll();
        request.getServletContext().setAttribute("front_noticeList",list);
        Words words = wordsService.getWords();
        words.setWords_date(new Date());
        request.getServletContext().setAttribute("words",words);  //init每日一句
        //用户推荐模块初始化
        // 如果有用户登陆，就加载用户喜好的文章
        //没有登陆，就加载热门文章
        List<Article> initUserLike_Article = new ArrayList<>(100);//要推荐给用户的文章集合
        if(request.getSession().getAttribute("user_id")!=null){ //如果登陆了
            Integer user_id = (Integer) request.getSession().getAttribute("user_id");
            List<User_like> user_likes = userService.selectLikeByUserId(user_id);  //获取当前用户的喜好标签
            Collections.sort(user_likes);
            if(user_likes.size()>=1){
                List<Article> likeArticleByLabel1 = articleService.selectArticleByLabelId(user_likes.get(0).getLabel_id());
                for(int i=0;i<likeArticleByLabel1.size();i++){
                    initUserLike_Article.add(likeArticleByLabel1.get(i));
                    if(initUserLike_Article.size()>=2)break;
                }
            }
            if(user_likes.size()>=2){
                List<Article> likeArticleByLabel2 = articleService.selectArticleByLabelId(user_likes.get(1).getLabel_id());
                for(int i=0;i<likeArticleByLabel2.size();i++){
                    initUserLike_Article.add(likeArticleByLabel2.get(i));
                    if(initUserLike_Article.size()>=4)break;
                }
            }
            List<Article> hot = articleService.selectArticleByView();  //获取热门文章
            int j=0;
            for(int i=initUserLike_Article.size();i<5;i++){
                initUserLike_Article.add(hot.get(j));
                j++;
            }

            request.getSession().setAttribute("user_article_list",initUserLike_Article);
        }else{
            List<Article> hot = articleService.selectArticleByView();  //获取热门文章
            request.getSession().setAttribute("user_article_list",hot);
        }

        if (sort_id!=null ){
            if(sort_id != 77){
                request.getSession().setAttribute("sort_id",sort_id);
                request.getSession().setAttribute("keyword","");
            }
            if(sort_id==77){
                request.getSession().setAttribute("sort_id",sort_id);
                System.out.println(keyword);
                request.getSession().setAttribute("keyword",keyword);
            }
        }else {
            request.getSession().setAttribute("sort_id", 0);
            request.getSession().setAttribute("keyword","");
        }
        return "front/index";
    }


    /**
     * GET
     * 根据请求,查询文章
     * @param sort 文章种类,0为无条件,1为前端技术,2为后端技术.....
     * @param request
     * @return
     */
    @RequestMapping(value = "index_get",method = RequestMethod.GET)
    public String indexGet(Integer sort_id,String keyword,HttpServletRequest request) {
        if (sort_id!=null ){
            if(sort_id != 77){
                request.getSession().setAttribute("sort_id",sort_id);
                request.getSession().setAttribute("keyword","");
            }
            if(sort_id==77){
                request.getSession().setAttribute("sort_id",sort_id);
                System.out.println(keyword);
                request.getSession().setAttribute("keyword",keyword);
            }
        }else {
            request.getSession().setAttribute("sort_id", 0);
            request.getSession().setAttribute("keyword","");
        }
        return "front/index";
    }


    /**
     * 获取用户详细信息
     * @param user_name
     * @return
     */
    @RequestMapping("userDetails")
    public ModelAndView userDetails(String user_name){
        ModelAndView modelAndView = new ModelAndView("front/user_details");
        User user = userService.getUserByName(user_name);
        Date date =  user.getUser_birthday();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        modelAndView.addObject("birthday",simpleDateFormat.format(date));
        user = UserUtil.setIsQQ(user);  //判断当前用户是否是qq登陆，为了显示qq头像做判断
        modelAndView.addObject("user",user);
        System.out.println(user.getUser_sex());
        modelAndView.addObject("user_age",super.getAgeByBirthday(user.getUser_birthday()));//计算年龄
        return modelAndView;
    }

    @Override
    public String getType() {
        return null;
    }

    @Override
    public String getFileUploadDir() {
        return "/uploadFiles/userPhoto";
    }
}
